<?php
/**
 * WithdrawModel.class.php
 * 提现模型
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2017-08-28
 */

namespace Common\Model;

class WithdrawModel extends BaseModel {

    protected $trueTableName    = 't_withdraw';
    protected $cache    = false;

    const MONEY_TYPE    = 3;
    
    /**
     * 字段解析
     * @param   $data
     * @param   $batch
     * @return  $data
     */
    static function resolveColumn($data, $batch = false){
        $status     = ['审核失败', '已放款', '待初审', '待复审', '放款失败'];
        $resolveColumn   = function(&$item) use ($status){
            $item['status_text']    = $status[$item['status']];
            $item['create_date']    = date('Y-m-d', $item['create_time']);
            if($item['auth_time'])
                $item['auth_date']  = date('Y-m-d', $item['auth_time']);
        };

        if($batch){
            foreach($data as &$item){
                $resolveColumn($item);
            }
        }else{
            $resolveColumn($data);
        }

        return $data;
    }

    /**
     * 查询条件设置
     * @param   $condition
     * @param   $tbName
     * @return  $where
     */
   function setCondition($condition, $tbName = ''){
        $where  = parent::setCondition($condition, $tbName);
        return $where;
    }

    /**
     * 数据列表获取
     * @param   $condition
     * @param   $page
     * @param   &$pageHtml
     * @return  $list
     */
    function getList($condition, $page, &$pageHtml){
        $where  = array_merge(
            $this->setCondition($condition, 'a'),
            D('User')->setCondition([
                'keyword' => $condition['keyword']
            ], 'b')
        );

        $query  = $this->table('t_withdraw a')
            ->join('left join t_user b on a.user_id = b.id')
            ->where($where)
            ->cache($this->cache);

        if($pageHtml === true){
            $Page   = new \Think\Page((clone $query)->count(), C('PAGE_COUNT'));
            $pageHtml   = $Page->angularShow();
        }

        $list   = $query
            ->page($page, C('PAGE_COUNT'))
            ->field('a.*, b.nickname, b.truename')
            ->select();

        return self::resolveColumn($list, true);
    }

    /**
     * 初审
     * @param   $id
     * @param   $result
     * @param   $remark
     * @param   $targetId   提现目标ID
     * @return  boolean
     */
    function firstAudit($id, $result, $remark, $targetId = 0){
        $info   = $this->where('id = %d and status = 2 and target_id = %d', $id, $targetId)->find();
        if(!$info){
            throw new \Exception('提现条目未找到');
        }
        if(!$result){
            return $this->_auditFail($info, $remark);
        }

        $info['status'] = 3;
        $info['remark'] = $remark;
        $info['auth_time']  = time();

        return $this->save($info);
    }

    /**
     * 复审
     * @param   $id
     * @param   $result
     * @param   $remark
     * @param   $targetId
     * @return  boolean
     */
    function secondAudit($id, $result, $remark, $targetId = 0){
        $info   = $this->where('id = %d and status = 3 and target_id = %d', $id, $targetId)->find();
        if(!$info){
            throw new \Exception('提现条目未找到');
        }
        if(!$result){
            return $this->_auditFail($info, $remark);
        }

        $userInfo   = D('User')->getItem(['id' => $info['user_id']]);
        if(!$userInfo){
            throw new \Exception('用户未找到');
        }

        //微信放款
        $rate   = (float)C('PLAT_CONFIG.wd_tax_rate');
        $amount     = $info['amount'] * (1 - $rate);
        $WxPay  = new \Wechat\Util\WxPay();
        $orderInfo  = $WxPay->transferToUser($userInfo['open_id'], $amount, '欣乐土提现');
        if($orderInfo === false){
            throw new \Exception($WxPay->errMsg);
        }

        //插入Money表
        $moneyId    = D('Money')->add([
            'user_id'   => $userInfo['id'],
            'trade_no'  => $orderInfo['partner_trade_no'],
            'goods_type'    => self::MONEY_TYPE,
            'goods_id'  => $info['id'],
            'amount'    => 0 - $amount,
            'create_time'   => time(),
            'achive_time'   => time(),
            'status'    => 1
        ]);

        //提现条目状态变更
        $info['status'] = 1;
        $info['tax_rate']   = $rate;
        $info['remark'] = $remark;
        $info['auth_time']  = time();

        return $this->save($info);
    }

    /**
     * 审核失败
     * @param   $info   提现条目
     * @param   $remark
     * @return  boolean
     */
    private function _auditFail($info, $remark){
        //将提现金额返至用户钱包
        $amount     = $info['amount'];
        $userInfo   = D('User')->where('id = %d', $info['user_id'])->setInc('wallet', $amount);
        
        //提现状态更改
        $info['status'] = 0;
        $info['remark'] = $remark;
        $info['auth_time']  = time();
        return $this->save($info);
    }
}